<script setup lang="ts">
import { computed, ref } from "vue";
import { flatMap } from "lodash-es";
import { useRoute } from "vue-router";

import { Edit } from "@element-plus/icons-vue";
import {
  ElButton,
  ElCard,
  ElCheckbox,
  ElCheckboxGroup,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRow,
  ElSkeleton,
  ElSwitch,
  ElTable,
  ElTableColumn,
  ElTag,
  ElTooltip,
} from "element-plus";

import AppFooter from "@/components/common/AppFooter.vue";
import ByDescription from "@/components/common/ByDescription.vue";
import DialogChoosePackage from "./components/DialogChoosePackage.vue";
import { ProInputNumber, ProRadioGroup } from "@/modules/package/form";
import ByDescriptionItem from "@/components/common/ByDescriptionItem.vue";
import DialogSkuModify from "./components/DialogSkuModify.vue";

import router from "@/router";
import ApiActivity from "@/api/activity";

import useEnum from "@/hooks/useEnum";
import useForm from "@/hooks/useForm";
import useTable from "@/hooks/useTable";
import useDialog from "@/hooks/useDialog";
import useRequest from "@/hooks/useRequest";

import { TActivity } from "@/global";
import { TSpec, TTicket, TTicketSkuList } from "@/types/global";

const { params } = useRoute();

const { get: getActivityStatus } = useEnum("EnumActivityStatus");
const { list: listStatus } = useEnum("EnumStatus");

const {
  refForm,
  model,
  isFetching: isSubmiting,
  reset,
  submit,
  onFetchResponse,
} = useForm<TTicket>(ApiActivity[params.id ? "ticketEdit" : "ticketAdd"], {
  defaultModel: {
    act_id: Number(params.act_id),
    sort: 255,
    status: 1,
  },
});

onFetchResponse(() => {
  ElMessage.success("操作成功！");
  router.go(-1);
});

// 正常状态的场次列表
const { list: listEtims } = useTable(ApiActivity.etimeList, {
  size: 2000,
  defaultSearch: {
    act_id: Number(params.act_id),
    status: 1,
    // etime_type: 1,
    // sort_dir: "asc",
    // sort: "create_time",
  },
});

// 规格列表
const { list: listSpecs } = useTable<TSpec>(ApiActivity.specList, {
  defaultSearch: { status: 1 },
});

// 获取活动详情
const { data, isFetching } = useRequest<{ detail: TActivity }>(
  ApiActivity.activityDetail,
  { defaultParams: { id: Number(params.act_id) } }
);
// 获取权益包详情
const {
  isFetching: isFetchingWithDetail,
  data: ticketDetail,
  onFetchResponse: onFetchResponseWithTicketDetail,
  refresh: refreshTicketDetail,
} = useRequest(ApiActivity.ticketDetail, {
  immediate: !!params.id,
  defaultParams: { id: +params.id },
});

onFetchResponseWithTicketDetail(() => {
  const { detail } = ticketDetail.value;
  const ticketJson = detail.specs ? JSON.parse(detail.specs) : [];

  model.value = {
    ...detail,
  };
  specSkuList.value = detail.sku_list;
  selectionEtims.value = ticketJson.etimes || [];
  selectionSpecs.value = ticketJson.specs || [];
});

const renderListSpecs = computed(() => {
  return listSpecs.value?.map((e) => {
    return {
      ...e,
      specValueList: e.spec_value.split(";").map(decodeURIComponent),
    };
  });
});

// 选择的场次
const selectionEtims = ref([]);
// 选择票种
const selectionSpecs = ref<number[][]>([]);
// 选择票种对象
const selectionSpecsObj = ref<any[][]>([]);
// 生产的规格列表
const specSkuList = ref<Omit<TTicketSkuList, "sold_num">[]>([]);

// 计算specList
const renderSpecList = () => {
  let list = [];
  // 计算场次信息
  const etimes = selectionEtims.value.map((e) => {
    const etimeItem = listEtims.value.find((ee) => ee.id === e);
    return etimeItem?.etime_title;
  });

  list.push({ name: "场次", value: etimes });

  // 计算票种信息
  selectionSpecs.value.forEach((e, index) => {
    if (e && e.length !== 0) {
      list.push({
        name: listSpecs.value[index].spec_name,
        value: e,
      });
    }
  });
  return list;
};

/**
 *  矫正数据
 *  强制清空之前的选项
 */
const correctionData = () => {
  selectionEtims.value = [];
  selectionSpecs.value = [];
  model.value.sku_list = [];
};

// 生产规格sku
const handleGenerateSpecMap = () => {
  specSkuList.value = [];
  selectionSpecsObj.value = [];

  selectionSpecs.value.forEach((e, index) => {
    const specName = listSpecs.value[index].spec_name;
    const specItem = [] as any[];
    if (e && e.length !== 0) {
      e.forEach((se) => {
        const specItemChild = {
          name: specName,
          value: se,
        };
        specItem.push(specItemChild);
      });
      selectionSpecsObj.value.push(specItem);
    }
  });

  const ticketSpecs = {
    etimes: selectionEtims.value,
    specs: selectionSpecs.value,
    specList: renderSpecList(),
  };

  const res = [selectionEtims.value, ...selectionSpecsObj.value].reduce(
    (ary, items) => {
      return flatMap(ary, (item) => items.map((e) => [...item, e]));
    },
    [[]] as any[][]
  );

  specSkuList.value = res.map(([etime, ...items]) => {
    const etimeItem = listEtims.value.find((e) => e.id === etime);

    let title = `场次:${etimeItem.etime_title}`;
    let key = `${etimeItem.etime_title}`;
    items.forEach((e: any) => {
      title += ` ${e.name}:${e.value}`;
      key += `;${e.value}`;
    });
    const obj = {
      etime_id: etime,
      sku_title: title,
      sku_name: key,
      sku_price: 0.0,
      spec_json: "",
      stock_num: 100,
      sale_limit: 1,
      package_id: 0,
      status: 1,
    } as TTicketSkuList;
    return obj;
  });

  model.value.sku_list = specSkuList.value;
  model.value.specs = JSON.stringify(ticketSpecs);
  model.value.etime_json = etimeJson.value;
  // console.log(etimeJson.value)
};

const rules = {
  ticket_title: { required: true, message: "请输入权益包标题" },
  // sort: { required: true, message: "请输入排序" },
  status: { required: true, message: "请设置权益包状态" },
  sku_list: { required: true, message: "请生成权益包" },
  // sku_list: {
  //   sku_price: { required: true, message: '请输入票面价格' },
  //   package_id: { required: true, message: '请选择权益模板' }
  // },
  // specs: {
  //     required: true,
  //     message: "请设置规则",
  //     validator(rule: any, values: any, callback: any) {
  //         if (values.length > 0) {
  //             callback();
  //         } else {
  //             callback(new Error("请设置规则  "));
  //         }
  //     }
  // },
};

const [visible, { source, open, close }] = useDialog();
// 选择package
const confirmChoosePackage = (data: any) => {
  source.value.package_id = data.id;
  source.value.package_name = data.package_title;
  close();
};
const etimeJson = computed(() => {
  // 计算场次信息
  let list: any = [];
  selectionEtims.value.map((e) => {
    const etimeItem = listEtims.value.find((ee) => ee.id === e);
    list.push({
      id: e,
      title: etimeItem.etime_title,
    });
  });
  return JSON.stringify(list);
});

/**
 * true 时，不需要重新生成/创建规格,
 * 仅允许单个编辑规格的库存和购买限制
 */
const disabledCreateSku = computed(() => data.value?.detail.status === 1);

//
const [showSkuDialog, { source: chooseSkuSource, ...handleSkuDialog }] =
  useDialog();
</script>

<template>
  <AppFooter v-if="!disabledCreateSku">
    <div class="py-3 text-center">
      <ElButton plain size="large" :disabled="isSubmiting" @click="reset"
        >重置
      </ElButton>
      <ElButton
        size="large"
        type="primary"
        :loading="isSubmiting"
        @click="submit"
        >保存
      </ElButton>
    </div>
  </AppFooter>

  <ElForm
    ref="refForm"
    :model="model"
    label-width="6em"
    label-position="left"
    :rules="rules"
    v-loading="isFetchingWithDetail"
    element-loading-text="正在加载数据"
  >
    <ElRow :gutter="16">
      <ElCol :span="24">
        <ElCard :header="`活动:${data?.detail.title}`" class="mb-4">
          <ElSkeleton v-if="isFetching" :rows="1" />
          <ByDescription v-else-if="data" :column="3">
            <ByDescriptionItem label="活动状态">
              <ElTag
                :type="getActivityStatus(data.detail.act_status, 'color ')"
              >
                {{ getActivityStatus(data.detail.act_status, "label") }}
              </ElTag>
            </ByDescriptionItem>

            <ByDescriptionItem label="活动时间">
              <!-- <div>开始时间{{ data.detail.start_time }} - {{ data.detail.end_time }}</div> -->
              <div>{{ data.detail.act_time }}</div>
            </ByDescriptionItem>

            <ByDescriptionItem label="活动地址">
              {{ data.detail.address }}
            </ByDescriptionItem>
          </ByDescription>
        </ElCard>
      </ElCol>

      <ElCol :span="24" class="mb-4">
        <ElCard header="权益包基本信息">
          <ElFormItem label="标题" prop="ticket_title">
            <ElInput v-model="model.ticket_title" />
          </ElFormItem>

          <ElRow :gutter="16">
            <ElCol :span="12">
              <ElFormItem label="状态" prop="status">
                <ProRadioGroup v-model="model.status" :options="listStatus" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="12">
              <ElFormItem label="排序" prop="sort">
                <ProInputNumber
                  v-model="model.sort"
                  :min="1"
                  :max="9999"
                  :precision="0"
                />
              </ElFormItem>
            </ElCol>
          </ElRow>

          <ElFormItem label="备注" prop="remark">
            <ElInput v-model="model.remark" type="textarea" />
          </ElFormItem>

          <ElFormItem label="场次" required>
            <ElCheckboxGroup v-model="selectionEtims">
              <template v-for="item in listEtims" :key="item.id">
                <ElCheckbox
                  v-if="item.etime_type != 2"
                  :value="item.id"
                  :label="item.etime_title"
                />
              </template>
            </ElCheckboxGroup>
          </ElFormItem>

          <ElFormItem
            v-for="(spec, index) in renderListSpecs"
            :key="spec.id"
            :label="spec.spec_name"
          >
            <template #label>
              <ElTooltip :content="spec.spec_name">
                <div class="ellipsis">{{ spec.spec_name }}</div>
              </ElTooltip>
            </template>

            <ElCheckboxGroup v-model="selectionSpecs[index]">
              <ElCheckbox
                v-for="(subItem, index) in spec.specValueList"
                :key="index"
                :value="subItem"
                :label="subItem"
              />
            </ElCheckboxGroup>
          </ElFormItem>

          <template v-if="!disabledCreateSku">
            <ElButton
              plain
              class="mt-4"
              size="large"
              type="primary"
              :disabled="selectionEtims.length == 0"
              @click="handleGenerateSpecMap()"
            >
              {{ selectionEtims.length == 0 ? "请选择场次" : "生成规格表" }}
            </ElButton>

            <ElButton
              plain
              class="mt-4"
              size="large"
              type="warning"
              @click="correctionData"
            >
              强制重置数据
            </ElButton>
          </template>
        </ElCard>
      </ElCol>

      <ElCol :span="24">
        <ElCard header="权益包规格列表">
          <!-- <ElTable :data="specSkuList"> -->
          <ElTable :data="model.sku_list">
            <!-- <ElTableColumn label="票券规格" prop="sku_title" /> -->

            <ElTableColumn label="规格名称" minWidth="280">
              <template #="{ row }">
                <ElInput v-model="row.sku_name" :disabled="disabledCreateSku" />
              </template>
            </ElTableColumn>

            <ElTableColumn label="规格价格(元)" width="121">
              <template #="{ row, $index }">
                <ElFormItem
                  class="mb-0"
                  label=""
                  label-width="0"
                  :prop="['sku_list', $index, 'sku_price']"
                  :rules="{
                    required: true,
                    type: 'number',
                    min: 0.01,
                    message: '请设置规格价格',
                  }"
                >
                  <ProInputNumber
                    v-model="row.sku_price"
                    :min="0.01"
                    :precision="2"
                    :max="9999999"
                    :disabled="disabledCreateSku"
                  />
                </ElFormItem>
              </template>
            </ElTableColumn>

            <ElTableColumn label="市场价格(元)" width="121">
              <template #="{ row, $index }">
                <ElFormItem
                  class="mb-0"
                  label=""
                  label-width="0"
                  :prop="['sku_list', $index, 'market_price']"
                  :rules="{
                    required: true,
                    type: 'number',
                    min: 0.01,
                    message: '请设置规格价格',
                  }"
                >
                  <ProInputNumber
                    v-model="row.market_price"
                    :min="0.01"
                    :precision="2"
                    :max="9999999"
                    :disabled="disabledCreateSku"
                  />
                </ElFormItem>
              </template>
            </ElTableColumn>

            <ElTableColumn label="早鸟价格(元)" width="121">
              <template #="{ row, $index }">
                <ElFormItem
                  class="mb-0"
                  label=""
                  label-width="0"
                  :prop="['sku_list', $index, 'early_price']"
                  :rules="{
                    required: true,
                    type: 'number',
                    min: 0.01,
                    message: '请设置规格价格',
                  }"
                >
                  <ProInputNumber
                    v-model="row.early_price"
                    :min="0.01"
                    :precision="2"
                    :max="9999999"
                    :disabled="disabledCreateSku"
                  />
                </ElFormItem>
              </template>
            </ElTableColumn>

            <ElTableColumn label="限购数量" width="121">
              <template #="{ row, $index }">
                <ElFormItem
                  class="mb-0"
                  label=""
                  label-width="0"
                  :prop="['sku_list', $index, 'sale_limit']"
                >
                  <ProInputNumber
                    v-model="row.sale_limit"
                    :min="0"
                    :precision="0"
                    :max="9999999"
                    :disabled="disabledCreateSku"
                  />
                </ElFormItem>
              </template>
            </ElTableColumn>

            <ElTableColumn label="库存(张)" width="120">
              <template #="{ row, $index }">
                <ElFormItem
                  class="mb-0"
                  label=""
                  label-width="0"
                  :prop="['sku_list', $index, 'sale_limit']"
                >
                  <ProInputNumber
                    v-model="row.stock_num"
                    :min="0"
                    :precision="0"
                    :max="9999999"
                    :disabled="disabledCreateSku"
                  />
                </ElFormItem>
              </template>
            </ElTableColumn>

            <ElTableColumn label="已售(张)" width="80">
              <template #="{ row }">
                {{ row.sold_num }}
              </template>
            </ElTableColumn>

            <ElTableColumn label="状态" width="60">
              <template #="{ row }">
                <ElSwitch
                  v-model="row.status"
                  inline-prompt
                  active-text="可用"
                  inactive-text="禁用"
                  :active-value="1"
                  :inactive-value="2"
                  :disabled="disabledCreateSku"
                />
              </template>
            </ElTableColumn>

            <ElTableColumn label="关联权益" minWidth="100">
              <template #="{ row, $index }">
                <ElFormItem
                  label-width="0"
                  :prop="['sku_list', $index, 'package_id']"
                  :rules="{
                    required: true,
                    type: 'number',
                    min: 1,
                    message: '请选择关联权益',
                  }"
                  :inline-message="false"
                >
                  <ElInput
                    readonly
                    :disabled="disabledCreateSku"
                    :value="row.package_name || row.package_id"
                    @click="open(row)"
                  />
                </ElFormItem>
              </template>
            </ElTableColumn>

            <ElTableColumn label="操作" width="100">
              <template #="{ row }">
                <ElButton
                  circle
                  :icon="Edit"
                  type="primary"
                  @click="handleSkuDialog.open(row)"
                />

                <!-- <ElButton circle :icon="Delete" type="danger" /> -->
              </template>
            </ElTableColumn>
          </ElTable>
        </ElCard>
      </ElCol>
    </ElRow>
  </ElForm>

  <DialogChoosePackage
    v-model="visible"
    @choosePackage="confirmChoosePackage"
  />

  <ElDialog
    v-model="showSkuDialog"
    center
    width="400px"
    title="编辑规格"
    destroy-on-close
  >
    <DialogSkuModify
      :source="chooseSkuSource"
      @success="
        handleSkuDialog.close();
        refreshTicketDetail();
      "
    />
  </ElDialog>
</template>
